﻿/*
 DotNetNuke - http://www.dotnetnuke.com
 Copyright (c) 2002-2010 by DotNetNuke Corp.

 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
 documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
 the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
 to permit persons to whom the Software is furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in all copies or substantial portions 
 of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
 TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
 CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
 DEALINGS IN THE SOFTWARE.

*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Xml;

using DotNetNuke.Common;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Modules.Actions;
using DotNetNuke.Modules.UserDefinedTable.Security;
using DotNetNuke.Security;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;
using DotNetNuke.UI.Skins;
using DotNetNuke.UI.Skins.Controls;
using DotNetNuke.UI.Utilities;
using DotNetNuke.UI.WebControls;


namespace DotNetNuke.Modules.UserDefinedTable
{


  /// <summary>
  /// The EditUserDefinedTable Class provides the basic UI for Editing the UserDefinedTable
  /// </summary>
  public partial class EditForm : UDTdataEditor, IActionable
  {
    
    private DataSet _data;
    private UserDefinedTableController _udtController;
    private CaptchaControl ctlCaptcha;
    private DotNetNuke.Modules.UserDefinedTable.EditControls EditControls;
    private bool HasDeletePermission;
    private bool HasUpdatePermission;
    private int UserDefinedRowId;



    protected override void OnInit(EventArgs e)
    {
      base.OnInit(e);

      this.Page.RegisterRequiresViewStateEncryption();
      this.BuildEditForm();

      //base.Init += new EventHandler(this.Page_Init);
      //base.Load += new EventHandler(this.Page_Load);

      cmdUpdate.Click += new EventHandler(cmdUpdate_Click);
      cmdCancel.Click += new EventHandler(cmdCancel_Click);
      cmdDelete.Click += new EventHandler(cmdDelete_Click);
    }





    //protected void Page_Load(object sender, EventArgs evt)
    protected override void OnLoad(EventArgs evt)
    {
      base.OnLoad(evt);

      try
      {
        if (Utilities.CBoolN((this.ModuleContext.Settings[SettingName.UseButtons]), false))
        {
          this.cmdCancel.Visible = false;
          this.cmdDelete.Visible = false;
          this.cmdUpdate.Visible = false;
        }
        else
        {
          this.cmdCancelButton.Visible = false;
          this.cmdDeleteButton.Visible = false;
          this.cmdUpdateButton.Visible = false;
        }
        if (!this.Page.IsPostBack)
        {
          ClientAPI.AddButtonConfirm(this.cmdDelete, DotNetNuke.Services.Localization.Localization.GetString("DeleteItem", this.LocalResourceFile));
          ClientAPI.AddButtonConfirm(this.cmdDeleteButton, DotNetNuke.Services.Localization.Localization.GetString("DeleteItem", this.LocalResourceFile));
        }
        if (!this.IsNewRow)
        {
          if (!this.Page.IsPostBack)
            //Clear all default values
            foreach (DotNetNuke.Modules.UserDefinedTable.EditControl control in this.EditControls.Values)
              control.Value = "";

          DataType type;
          string sValue;

          foreach(DataRow field in this.Data.Tables[DataSetTableName.Fields].Rows)
          {

            type = DataType.ByName(Utilities.CStrN((field[FieldsTableColumn.Type]), ""));
            sValue = (string)this.CurrentRow[(string)field[FieldsTableColumn.Title]]; 

            if (!type.IsSeparator)
            {
              if (!this.Page.IsPostBack)
                this.EditControls[(string)field[FieldsTableColumn.Title]].Value = sValue;

              if ((string)field[FieldsTableColumn.Type] == "CreatedBy")
                this.CheckPermission(sValue);

            }
          }
        }
        else
        {
          this.cmdDelete.Visible = false;
          this.cmdDeleteButton.Visible = false;
          this.CheckPermission();

          if (!this.Page.IsPostBack && (Utilities.CIntN(this.Request.QueryString["OnSubmit"]) == this.ModuleContext.ModuleId))
            this.ShowUponSubmit();
          
        }
      }
      catch (Exception e)
      {
        Exception exc = e;
        DotNetNuke.Services.Exceptions.Exceptions.ProcessModuleLoadException((PortalModuleBase)this, exc);
        this.CheckPermission(false);
      }
    }





    private void BuildCssForm(List<FormColumnInfo> EditForm)
    {

      if (EditForm == null)
        return;

      this.placeholderEditForm.Visible = true;
      this.tblEditForm.Visible = false;
      Control placeholderEditForm = this.placeholderEditForm;

      foreach (FormColumnInfo current in EditForm)
      {
        if (current.IsNewFieldSet)
        {
          HtmlGenericControl control2 = new HtmlGenericControl("fieldset");
          control2.Attributes.Add("class", "UDT_Field");

          if (!string.IsNullOrEmpty(current.Title))
          {
            HtmlGenericControl child = new HtmlGenericControl("legend");
            child.Controls.Add(new LiteralControl(current.Title));
            control2.Controls.Add(child);
          }
          placeholderEditForm = control2;
          control2.Visible = current.Visible;
          this.placeholderEditForm.Controls.Add(placeholderEditForm);
        }
        else if (current.IsSeparator && current.Visible)
          placeholderEditForm.Controls.Add(this.GetSeparator(current.Title));

        else
        {
          FormColumnInfo info2 = current;
          HtmlGenericControl control5 = new HtmlGenericControl("div");
          control5.Attributes.Add("class", string.Format("UDT_Field UDT_Type_{0}", info2.FieldType));
          HtmlGenericControl control4 = new HtmlGenericControl("div");
          control4.Attributes.Add("class", "UDT_Caption");
          string required = Utilities.CStrN(current.Required ? Localization.GetString("RequiredIndicator", LocalResourceFile) : "");

          control4.Controls.Add(this.GetTitleControl(info2.Title, info2.Help, required));
          control5.Controls.Add(control4);

          if (info2.EditControl != null)
          {
            HtmlGenericControl control6 = new HtmlGenericControl("div");
            control6.Attributes.Add("class", "UDT_Input");
            control6.Controls.Add(info2.EditControl);
            control5.Controls.Add(control6);
          }
          control5.Visible = info2.Visible;
          if (!info2.IsUserDefinedField)
            placeholderEditForm = this.placeholderEditForm;

          placeholderEditForm.Controls.Add(control5);
          info2 = null;
        }
      }
    }





    private void BuildEditForm()
    {

      List<FormColumnInfo> editForm = new List<FormColumnInfo>();
      FormColumnInfo item;
      ModuleSecurity security = new ModuleSecurity(this.ModuleContext);

      this.EditControls = new EditControls(this.ModuleContext);

      string FieldTitle, dataTypeName;
      DataType type;
      bool IsColumnEditable;

      foreach(DataRow current in this.Data.Tables[DataSetTableName.Fields].Rows)
      {
        FieldTitle = Utilities.CStrN((current[FieldsTableColumn.Title]), "");
        dataTypeName = Utilities.CStrN((current[FieldsTableColumn.Type]), "");
        type = DataType.ByName(dataTypeName);

        IsColumnEditable = (!type.SupportsHideOnEdit || Convert.ToBoolean(current[FieldsTableColumn.ShowOnEdit]))
          && (!Convert.ToBoolean(current[FieldsTableColumn.IsPrivate]) || security.IsAllowedToEditAllColumns());

        //If Column is hidden, the Fieldtype falls back to "String"
        //as the related EditControl works perfect even if it is not visibile
        //EditControls of other user defined datatypes may use core controls 
        //(e.g. UrlControl or RTE) which are not rock solid regarding viewstate. 
        if (!IsColumnEditable && type.IsUserDefinedField)
          dataTypeName = "String";

        item = new FormColumnInfo();
        item.IsUserDefinedField = type.IsUserDefinedField;

        if (type.IsSeparator)
        {
          item.IsNewFieldSet = Convert.ToBoolean(current[FieldsTableColumn.NormalizeFlag]);
          item.IsSeparator = true;

          if (Utilities.CBoolN((current[FieldsTableColumn.Visible]), false))
            item.Title = FieldTitle;

          item.Visible = IsColumnEditable;
        }
        else
        {
          item.Help = Utilities.CStrN((current[FieldsTableColumn.HelpText]), "");
          item.Title = Utilities.CStrN((current[FieldsTableColumn.Title]), "");
          item.Required = Utilities.CBoolN((current[FieldsTableColumn.Required]), false) & type.IsUserDefinedField;
          item.EditControl = this.EditControls.Add(
            Utilities.CStrN((current[FieldsTableColumn.Title]), "")
            , dataTypeName, (int)current[FieldsTableColumn.Id]
            , Utilities.CStrN((current[FieldsTableColumn.HelpText]), "")
            , Utilities.CStrN((current[FieldsTableColumn.Default]), "")
            , Utilities.CBoolN((current[FieldsTableColumn.Required]), false)
            , Utilities.CStrN((current[FieldsTableColumn.ValidationRule]), "")
            , Utilities.CStrN((current[FieldsTableColumn.ValidationMessage]), "")
            , Utilities.CStrN((current[FieldsTableColumn.EditStyle]), "")
            , Utilities.CStrN((current[FieldsTableColumn.InputSettings]), "")
            , Utilities.CStrN((current[FieldsTableColumn.OutputSettings]), "")
            , Utilities.CBoolN((current[FieldsTableColumn.NormalizeFlag]), false)
            ,this
          );
          item.Visible = IsColumnEditable;
        }
        editForm.Add(item);
      }

      if (this.CaptchaNeeded())
      {
        item = new FormColumnInfo();
        item.Title = DotNetNuke.Services.Localization.Localization.GetString("Captcha.Text", this.LocalResourceFile);
        this.ctlCaptcha = new CaptchaControl();
        this.ctlCaptcha.ID = "Captcha";
        this.ctlCaptcha.CaptchaWidth = Unit.Pixel(130);
        this.ctlCaptcha.CaptchaHeight = Unit.Pixel(40);
        this.ctlCaptcha.ToolTip = "CAPTCHA";
        this.ctlCaptcha.CssClass = "Normal";
        this.ctlCaptcha.ErrorMessage = DotNetNuke.Services.Localization.Localization.GetString("CaptchaError.Text", this.LocalResourceFile);
        item.EditControl = this.ctlCaptcha;
        item.Visible = true;
        item.IsUserDefinedField = false;
        editForm.Add(item);
      }
      if (Utilities.CBoolN((this.ModuleContext.Settings[SettingName.TableFreeEditForm]), false))
        this.BuildCssForm(editForm);
      
      else
        this.BuildFormAsTable(editForm);
      
      if (this.IsNewRow && Utilities.CStrN((this.ModuleContext.Settings[SettingName.ListOrForm]), "Form").Contains("Form"))
      {
        this.cmdUpdate.Attributes["resourcekey"] = "cmdSend.Text";
        this.cmdUpdateButton.Attributes["resourcekey"] = "cmdSend.Text";
      }
    }





    private void BuildFormAsTable(List<FormColumnInfo> EditForm)
    {

      if (EditForm == null)
        return;

      this.placeholderEditForm.Visible = false;
      this.tblEditForm.Visible = true;

      foreach (FormColumnInfo current in EditForm)
      {
        TableRow row = new TableRow();
        TableCell cell2 = new TableCell();
        cell2.VerticalAlign = VerticalAlign.Top;
        TableCell cell = cell2;

        if (!current.IsSeparator)
          cell.Controls.Add(this.GetTitleControl(current.Title, current.Help, ""));

        else
          cell.Controls.Add(this.GetSeparator(current.Title));

        if (current.EditControl == null)
        {
          cell.ColumnSpan = 3;
          row.Cells.Add(cell);
        }
        else
        {
          cell.CssClass = "SubHead";
          cell.Width = Unit.Pixel(200);
          row.Cells.Add(cell);
          cell = new TableCell();
          cell.Attributes["valign"] = "top";
          cell.CssClass = "NormalBold";

          if (current.Required)
            cell.Controls.Add(new LiteralControl(DotNetNuke.Services.Localization.Localization.GetString("RequiredIndicator", this.LocalResourceFile)));

          row.Cells.Add(cell);
          cell = new TableCell();
          cell.VerticalAlign = VerticalAlign.Top;
          cell.Controls.Add(current.EditControl);
          cell.Width = Unit.Percentage(80.0);
          row.Cells.Add(cell);
          row.Visible = current.Visible;
        }
        this.tblEditForm.Rows.Add(row);

        if (Utilities.CBoolN((this.ModuleContext.Settings[SettingName.ControlFullWidth]), false))
          this.tblEditForm.Width = Unit.Percentage(100.0);

      }
    }






    private bool CaptchaNeeded()
    {
      return ((this.ModuleContext.PortalSettings.UserId == -1) && Convert.ToBoolean(this.ModuleContext.Settings[SettingName.ForceCaptchaForAnonymous]));
    }




    private void cmdCancel_Click(object sender, EventArgs evt)
    {
      try
      {
        if (Utilities.CStrN((this.ModuleContext.Settings[SettingName.ListOrForm]), "List").Contains("Form"))
          this.Response.Redirect(this.Request.RawUrl);
        
        else
          this.Response.Redirect(DotNetNuke.Common.Globals.NavigateURL(this.ModuleContext.TabId), true);
        
      }
      catch (Exception e)
      {

        Exception exc = e;
        DotNetNuke.Services.Exceptions.Exceptions.ProcessModuleLoadException((PortalModuleBase)this, exc);

      }
    }




    private void cmdDelete_Click(object sender, EventArgs evt)
    {
      if (this.HasDeletePermission)
      {
        try
        {
          FileDataTypeRowDelete(); //updated by asida@centrum.cz
          this.UdtController.DeleteRow(this.UserDefinedRowId);
          this.Response.Redirect(DotNetNuke.Common.Globals.NavigateURL(this.ModuleContext.TabId), true);
        }
        catch (Exception e)
        {
          Exception exc = e;
          DotNetNuke.Services.Exceptions.Exceptions.ProcessModuleLoadException((PortalModuleBase)this, exc);
        }
      }
    }





    private void cmdUpdate_Click(object sender, EventArgs evt)
    {
      if (this.HasUpdatePermission)
      {
        try
        {
          string str = string.Empty;
          bool flag2 = this.ModuleContext.PortalSettings.UserId == -1;
          bool flag = flag2;

          if (!flag2 && this.ModuleContext.Settings.ContainsKey(SettingName.ForceInputFiltering))
            flag = bool.Parse((string)this.ModuleContext.Settings[SettingName.ForceInputFiltering]);
          
          foreach (DotNetNuke.Modules.UserDefinedTable.EditControl control in this.EditControls.Values)
            if (!control.IsValid())
              str = str + string.Format("<li><b>{0}</b><br />{1}</li>", control.FieldTitle, control.ValidationMessage);
            
          if (this.CaptchaNeeded() && !this.ctlCaptcha.IsValid)
            str = str + string.Format("<li><b>{0}</b><br />{1}</li>", DotNetNuke.Services.Localization.Localization.GetString("Captcha.Text", this.LocalResourceFile), DotNetNuke.Services.Localization.Localization.GetString("CaptchaError.Text", this.LocalResourceFile));

          if ( string.IsNullOrEmpty(str) )
          {
            FileDataTypeRowUpdate(); //updated by asida@centrum.cz
            foreach (DotNetNuke.Modules.UserDefinedTable.EditControl control2 in this.EditControls.Values)
            {
              string str2 = control2.Value;
              this.CurrentRow[control2.FieldTitle] = str2;
            }
            this.UdtController.UpdateRow(this.Data);
            switch (Utilities.CStrN((this.ModuleContext.Settings[SettingName.ListOrForm]), "List"))
            {
              case "List":
                this.Response.Redirect(DotNetNuke.Common.Globals.NavigateURL(this.ModuleContext.TabId), true);
                return;

              case "FormAndList":
              case "ListAndForm":
                if (this.IsNewRow)
                  this.Response.Redirect(this.Request.RawUrl, true);
                
                else
                  this.Response.Redirect(DotNetNuke.Common.Globals.NavigateURL(this.ModuleContext.TabId), true);
                
                return;

              case "Form":
                {
                  string str5 = Utilities.CStrN((this.ModuleContext.Settings[SettingName.UponSubmitAction]), "Text");
                  if (str5 == "Text")
                  {
                    this.Controls.Clear();
                    this.ShowUponSubmit();
                    return;
                  }
                  if (str5 == "Form")
                    this.Response.Redirect(DotNetNuke.Common.Globals.NavigateURL(this.ModuleContext.TabId, "", new string[] { string.Format("OnSubmit={0}", this.ModuleId) }), true);
                  
                  else
                  {
                    string link = Utilities.CStrN((this.ModuleContext.Settings[SettingName.UponSubmitRedirect]), DotNetNuke.Common.Globals.NavigateURL(this.ModuleContext.TabId));
                    this.Response.Redirect(DotNetNuke.Common.Globals.LinkClick(link, this.ModuleContext.TabId, this.ModuleContext.ModuleId));
                  }
                  break;
                }
            }
          }
          else
          {
            PortalModuleBase objControl = (PortalModuleBase)(this.Parent is PortalModuleBase ? this.Parent : this);
            Skin.AddModuleMessage(objControl, string.Format("<ul>{0}</ul>", str), ModuleMessage.ModuleMessageType.YellowWarning);
          }
        }
        catch (Exception e)
        {

          Exception exc = e;
          DotNetNuke.Services.Exceptions.Exceptions.ProcessModuleLoadException((PortalModuleBase)this, exc);

        }
      }
    }





    private Control GetSeparator(string title)
    {
      if ( string.IsNullOrEmpty(title) )
        return new LiteralControl("<hr class=\"UDT_Separator\"/>");
      
      return new LiteralControl(string.Format("<div class=\"Head UDT_Separator\">{0}<hr/></div>", title));
    }





    private Control GetTitleControl(string title, string help, string required)
    {
      string str = string.Format("{0}:{1,-2}", title, required);
      if ( string.IsNullOrEmpty(help) )
      {
        Label label = new Label();
        label.Text = str;
        label.CssClass = "SubHead";
        return label;
      }
      PropertyLabelControl control3 = new PropertyLabelControl();
      control3.ID = string.Format("{0}_label", XmlConvert.EncodeName(title));
      control3.Caption = str;
      control3.ToolTip = help;
      control3.HelpText = help;
      PropertyLabelControl control2 = control3;
      control2.HelpStyle.CssClass = "Help";
      control2.LabelStyle.CssClass = "SubHead";
      return control2;
    }





    private bool HasAddPermissonByQuota()
    {
      int userRecordQuota = Utilities.CIntN((this.ModuleContext.Settings[SettingName.UserRecordQuota]));
      if (userRecordQuota > 0)
      {
        DataSet dataSet = this.UdtController.GetDataSet(false);
        return ModuleSecurity.HasAddPermissonByQuota(dataSet.Tables[DataSetTableName.Fields], dataSet.Tables[DataSetTableName.Data], userRecordQuota, this.UserInfo.Username);
      }
      return true;
    }





    private void CheckPermission()
    {
      this.CheckPermission(true);
    }





    private void CheckPermission(bool isUsersOwnItem)
    {
      ModuleSecurity security = new ModuleSecurity(this.ModuleContext);
      if ((this.IsNewRow || !security.IsAllowedToEditRow(isUsersOwnItem)) && ((!this.IsNewRow || !security.IsAllowedToAddRow()) || !this.HasAddPermissonByQuota()))
      {
        if (this.Parent is PortalModuleBase)
        {
          this.cmdUpdate.Enabled = false;
          this.cmdUpdateButton.Enabled = false;
          this.divForm.Visible = true;
        }
        else
          this.Response.Redirect(DotNetNuke.Common.Globals.NavigateURL(this.ModuleContext.TabId), true);
        
      }
      else
        this.HasUpdatePermission = true;
      
      this.HasDeletePermission = security.IsAllowedToDeleteRow(isUsersOwnItem) & !this.IsNewRow;
      bool flag = Utilities.CBoolN((this.ModuleContext.Settings[SettingName.UseButtons]), false);
      this.cmdDelete.Visible = this.HasDeletePermission & !flag;
      this.cmdDeleteButton.Visible = this.HasDeletePermission & flag;
    }





    private void CheckPermission(string CreatedBy)
    {
      this.CheckPermission((this.ModuleContext.PortalSettings.UserInfo.Username == CreatedBy) && (CreatedBy != Definition.NameOfAnonymousUser));
    }






    private void ShowUponSubmit()
    {
      HtmlGenericControl control2 = new HtmlGenericControl("div");
      control2.InnerHtml = (string)this.ModuleContext.Settings[SettingName.SubmissionText];
      HtmlGenericControl child = control2;
      child.Attributes["class"] = "Normal UDT_UponSubmit";
      this.Controls.Add(child);
    }





    private DataRow CurrentRow
    {
      get
      {
        if (this.Data.Tables[DataSetTableName.Data].Rows.Count == 0)
        {
          DataRow row = this.Data.Tables[DataSetTableName.Data].NewRow();
          row[DataTableColumn.RowId] = this.UserDefinedRowId;
          this.Data.Tables[DataSetTableName.Data].Rows.Add(row);
        }
        return this.Data.Tables[DataSetTableName.Data].Rows[0];
      }
    }





    private DataSet Data
    {
      get
      {

        if (this._data == null)
        {
          if (!int.TryParse(this.Request.QueryString[DataTableColumn.RowId], out this.UserDefinedRowId))
            this.UserDefinedRowId = -1;
          
          this._data = this.UdtController.GetRow(this.UserDefinedRowId);
        }

        return this._data;
      }
    }





    ModuleActionCollection DotNetNuke.Entities.Modules.IActionable.ModuleActions
    {
      get
      {
        ModuleActionCollection actions = new ModuleActionCollection();
        ModuleSecurity security = new ModuleSecurity(this.ModuleId, this.TabId, this.Settings);

        if (security.IsAllowedToViewList() && (Utilities.CStrN((this.Settings[SettingName.ListOrForm]), "") == "Form"))
        {
          string url = DotNetNuke.Common.Globals.NavigateURL(this.TabId, "", new string[] { "show=records" });
          actions.Add(this.ModuleContext.GetNextActionID(), DotNetNuke.Services.Localization.Localization.GetString("List.Action", this.LocalResourceFile), "AddContent.Action", "", "~/images/view.gif", url, false, SecurityAccessLevel.View, true, false);
        }

        return actions;
      }
    }





    private bool IsNewRow
    {
      get
      {
        return (this.UserDefinedRowId == -1);
      }
    }





    public ModuleActionCollection ModuleActions
    {
      get
      {
        ModuleActionCollection actions = new ModuleActionCollection();
        ModuleSecurity security = new ModuleSecurity(this.ModuleId, this.TabId, this.Settings);
        if (security.IsAllowedToViewList() && (Utilities.CStrN((this.Settings[SettingName.ListOrForm]), "") == "Form"))
        {
          string url = DotNetNuke.Common.Globals.NavigateURL(this.TabId, "", new string[] { "show=records" });
          actions.Add(this.ModuleContext.GetNextActionID(), DotNetNuke.Services.Localization.Localization.GetString("List.Action", this.LocalResourceFile), "AddContent.Action", "", "~/images/view.gif", url, false, SecurityAccessLevel.View, true, false);
        }
        return actions;
      }
    }





    private UserDefinedTableController UdtController
    {
      get
      {
        if (this._udtController == null)
          this._udtController = new UserDefinedTableController(this.ModuleContext);
        
        return this._udtController;
      }
    }




  }

}

